//
// Highlight.cs
//
// Author: 
//  Fredy Ramirez <framirez@pacificcoolwave.com>
//
// Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)
//
//  Creation date: Oct 12, 2011
//  Last modification: 

/*
The MIT License

Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */


using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Reflection;
using Pcw.Addins.Highlighting.Definition;
using Gtk;
using System.Text.RegularExpressions;
using Pcw.PcwTextEditor.PcwDocument;

namespace Pcw.Addins.Highlighting
{
	public class Highlight
	{
		private Dictionary<string, HighlightDefinition> defs = new Dictionary<string, HighlightDefinition>();
		
		public Dictionary<string, HighlightDefinition> Defs {
			get {
				return defs;
			}
		}
		
		/// <summary>
		/// Initializes a new instance of the <see cref="Pcw.Addins.Highlighting.Highlight"/> class wtih no parameters.
		/// It loads a definition xml file from a default location (dllPath/syntax)
		/// </summary>	
		public Highlight () : this(Path.Combine (Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Path.Combine ("syntax", "definition.xml")))
		{
		}		
		
		/// <summary>
		/// Initializes a new instance of the <see cref="Pcw.Addins.Highlighting.Highlight"/> class.
		/// </summary>
		/// <param name="definitionFile">
		///   <see cref="System.String"/> Definition file.
		/// </param>
		public Highlight (string definitionFile)
		{
			if (!File.Exists(definitionFile))
				throw new ApplicationException("Could not find definition file: '" + definitionFile + "' for addin Pcw.Highlighting");
			
			GetDefinitions(definitionFile);
		}
		
		/// <summary>
		/// Initializes a new instance of the <see cref="Pcw.Addins.Highlighting.Highlight"/> class.
		/// </summary>
		/// <param name="definitionStringReader">
		///   <see cref="System.IO.StringReader"/> object representing the definition file.
		/// </param>
		public Highlight (StringReader definitionStringReader)
		{
			if (definitionStringReader == null)
				throw new ApplicationException("The definition StringReader object is null for addin Pcw.Highlighting");
			
			GetDefinitions(definitionStringReader);
		}		
		
		/// <summary>
		/// Get the HighlightDefinition object for an specific extension using the syntax file defined in definition.xml file.
		/// </summary>
		/// <param name="ext">
		///   <see cref="System.String"/> file extension.
		/// </param>
		/// <returns>
		///  A <see cref="Pcw.Addins.Highlighting.HighlightDefinition"/> object.
		/// </returns>
		public HighlightDefinition GetDefinitionForExtension(string ext) 
		{
			foreach (KeyValuePair<string, HighlightDefinition> d in defs)
				if (d.Value.IsExtension(ext))
					return d.Value;
			
			return null;
		}
		
		/// <summary>
		/// Get the HighlightDefinition object for an specific extension.
		/// </summary>
		/// <param name="ext">
		///   <see cref="System.String"/> file extension.
		/// </param>
		/// <param name="syntaxFile">
		///   <see cref="System.String"/> syntax file.
		/// </param>
		/// <returns>
		///  A <see cref="Pcw.Addins.Highlighting.HighlightDefinition"/> object.
		/// </returns>
		public HighlightDefinition GetDefinitionForExtension(string ext, string syntaxFile) 
		{
			foreach (KeyValuePair<string, HighlightDefinition> d in defs)
			{
				if (d.Value.IsExtension(ext, syntaxFile))
					return d.Value;
			}
			
			return null;
		}

		/// <summary>
		/// Get the HighlightDefinition object for an specific extension.
		/// </summary>
		/// <param name="ext">
		///   <see cref="System.String"/> file extension.
		/// </param>
		/// <param name="syntaxFile">
		///   <see cref="System.IO.StringReader"/> object representing syntax.
		/// </param>
		/// <returns>
		///  A <see cref="Pcw.Addins.Highlighting.HighlightDefinition"/> object.
		/// </returns>		
		public HighlightDefinition GetDefinitionForExtension(string ext, StringReader reader) 
		{
			foreach (KeyValuePair<string, HighlightDefinition> d in defs)
			{
				if (d.Value.IsExtension(ext, reader))
					return d.Value;
			}
			
			return null;
		}		
		
		public void ApplyHighlight(TextBuffer buffer, HighlightDefinition def, HighlightBlocks blocks) 
		{
			ApplyHighlight(buffer, null, def, blocks);
		}
				
		public void ApplyHighlight(TextBuffer buffer, TextChangedInfo info, HighlightDefinition def, HighlightBlocks blocks) 
		{			
			if (info != null) {  // Document has changed 
				def.Descriptors.ApplyHighlightChanged(buffer, info, blocks);
				return;
			}
			
			// Document just loaded
			VerifyBufferTags(buffer, def);
			def.Descriptors.ApplyHighlightLoading(buffer, blocks);
		}
	
		private void GetDefinitions(string definitionFile)
		{
			XmlDocument document = new XmlDocument();
			document.Load(definitionFile);
			GetDefinitions(document);
		}

		private void GetDefinitions(StringReader definitionStringReader)
		{
			XmlDocument document = new XmlDocument();
			document.Load(definitionStringReader);
			GetDefinitions(document);
		}
		
		private void GetDefinitions(XmlDocument document)
		{			
			foreach (XmlNode node in document.DocumentElement.ChildNodes) 
			{
				if (node.NodeType != XmlNodeType.Comment) {
					XmlElement item = (XmlElement)node;				
					defs.Add(XmlUtil.GetString(item, "name"), new HighlightDefinition(XmlUtil.GetString(item, "label"), 
						XmlUtil.GetString(item, "file"), XmlUtil.GetString(item, "extensions")));
				}
			}
		}
		
		private void VerifyBufferTags(TextBuffer buffer, HighlightDefinition def)
		{
			foreach (Descriptor d in def.Descriptors.DescriptorList)
				if (buffer.TagTable.Lookup(d.TagName) == null) 
					buffer.TagTable.Add (d.GetTextTag());
		}
	}
}

